package com.xiao.newfarm.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiaoxiaoping
 * @Date 2020/5/28 10:42
 * @Version 1.0
 */
@Component
public class RedisUtil {
	
	private static final Logger logger = (Logger) LoggerFactory.getLogger(RedisUtil.class);
	
	@Resource
	private  RedisTemplate<String,Object> template;
	
	/**
	 * @param: [key]
	 * @return: java.lang.String
	 * @author: xiaoxiaoping
	 * @date: 2020/5/28 10:53
	 * 获取值
	 */
	public  Object get(String key) {
		try {
			return template.opsForValue().get(key);
		}catch (Exception ex){
			return null;
		}
	}
	
	/**
	 * @param: [key, value]
	 * @return: void
	 * @author: xiaoxiaoping
	 * @date: 2020/5/28 10:54
	 * 设置值
	 */
	public   void set(String key, Object value) {
		template.opsForValue().set(key, value);
	}
	
	
	/**
	 * 指定缓存
	 * @param key
	 * @param time
	 * @return
	 */
	public  boolean expire(String key,long time){
		try {
			if (time > 0) {
				template.expire(key, time, TimeUnit.SECONDS);
			}
			return true;
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return false;
		}
	}
	
	/**
	 * 普通缓存放入并设置时间
	 * @param key
	 * @param value
	 * @param time 时间（秒） time要大于0 如果小于等于0 加设置无限期
	 * @return
	 */
	public  boolean set(String key,Object value,long time){
		try{
			if(time>0) {
				template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
			}else{
				set(key,value);
			}
			return true;
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return false;
		}
	}
	
	
	/**
	 * 判断key是否存在
	 * @param key
	 * @return true 存在 false不存在
	 */
	public  boolean hasKey(String key){
		try{
			return template.hasKey(key);
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return false;
		}
	}
	
	/**
	 * 删除缓存
	 * @param key 可以传一个值 或者多个
	 */
	public   void del(String... key){
		if(null != key && key.length>0){
			if(key.length==1) {
				template.delete(key[0]);
			}else {
				template.delete(CollectionUtils.arrayToList(key));
			}
		}
	}
	
	/**
	 * 递增
	 * @param key
	 * @param delta 要增加多少（大于0）
	 * @return
	 */
	public  long incr(String key,long delta){
		if(delta<0){
			throw  new RuntimeException("递增因子必须大于0");
		}
		return template.opsForValue().increment(key,delta);
	}
	/**
	 * 递减
	 * @param key 键
	 * @param delta 要减少几(小于0)
	 * @return
	 */
	public   long decr(String key, long delta) {
		if (delta < 0) {
			throw new RuntimeException("递减因子必须大于0");
		}
		return template.opsForValue().increment(key, -delta);
	}
	
}
